package drds.plus.repository.mysql.function.all;

import drds.plus.common.jdbc.SetParameterMethodAndArgs;
import drds.plus.executor.function.scalar.filter.Filter;
import drds.plus.repository.mysql.execute_plan_to_sql.ExecutePlanVisitor;
import drds.plus.repository.mysql.function.FunctionStringConstructor;
import drds.plus.sql_process.abstract_syntax_tree.execute_plan.ExecutePlan;
import drds.plus.sql_process.abstract_syntax_tree.expression.item.function.Function;
import drds.plus.sql_process.abstract_syntax_tree.expression.item.function.Operation;
import drds.plus.sql_process.type.Type;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class GreaterEqualAll implements FunctionStringConstructor {

    public String constructColumnNameForFunction(ExecutePlan query, boolean bindVal, AtomicInteger bindValSequence, Map<Integer, SetParameterMethodAndArgs> paramMap, Function function, ExecutePlanVisitor parentVisitor) {
        StringBuilder sb = new StringBuilder();

        sb.append(parentVisitor.getNewExecutePlanVisitor(function.getArgList().get(0)).getString());

        Object right = function.getArgList().get(1);

        // 右边被提前计算过了，找出最大值，转成>=
        if (right instanceof List) {

            Type type = ((Filter) function.getExtraFunction()).getArgType();
            Object max = Collections.max((List) right, type);

            sb.append(" >= ");
            sb.append(parentVisitor.getNewExecutePlanVisitor(max).getString());
        } else {
            // 右边没进行计算，还是个子查询，理论上不会发生
            sb.append(" >= all (");
            sb.append(parentVisitor.getNewExecutePlanVisitor(function.getArgList().get(1)).getString());
            sb.append(")");
        }

        return sb.toString();

    }

    public String[] getFunctionNames() {
        return new String[]{Operation.greater_than_or_equal_all.getOperationString()};
    }

}
